
package com.cgw.room.util;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;

import androidx.fragment.app.Fragment;

public class PhotoUtils {
    public final static int CAMERA = 1;

    public final static int GALLERY = 2;

    public static String pickPhoto(Activity activity, int source, int requestCode) {
        String filePath = null;
        if (source == CAMERA) {
            filePath = startCamera(activity, requestCode);
        } else if (source == GALLERY) {
            startGallery(activity, requestCode);
        }
        return filePath;
    }

    public static String pickPhoto(Fragment fragment, int source, int requestCode) {
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        String filePath = null;
        if (source == CAMERA) {
            filePath = startCamera(fragment, requestCode);
        } else if (source == GALLERY) {
            startGallery(fragment, requestCode);
        }
        return filePath;
    }

    private static String startCamera(Fragment fragment, int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String path = FileUtil.getCacheImagePath(fragment.getContext());
        Uri photoUri = Uri.parse("file://" + path);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        fragment.startActivityForResult(intent, requestCode);
        return path;
    }

    private static String startCamera(Activity context, int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        String path = FileUtil.getCacheImagePath(context);
        Uri photoUri = Uri.parse("file://" + path);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        context.startActivityForResult(intent, requestCode);
        return path;
    }

    private static void startGallery(Fragment fragment, int reqeustCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        try {
            fragment.startActivityForResult(intent, reqeustCode);
        } catch (ActivityNotFoundException e) {
        }
    }

    private static void startGallery(Activity fragment, int reqeustCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        try {
            fragment.startActivityForResult(intent, reqeustCode);
        } catch (ActivityNotFoundException e) {
        }
    }

}
